package cn.com.fstar.framework.admin.service;

import cn.com.fstar.core.model.Tuser;
import cn.com.fstar.core.model.TuserLogs;
import cn.com.fstar.core.pageModel.AdminLogs;
import cn.com.fstar.core.pageModel.PageHelper;
import cn.com.fstar.core.pageModel.UserLogs;
import cn.com.fstar.core.util.StringUtil;
import cn.com.fstar.framework.base.dao.BaseDaoI;
import cn.com.fstar.framework.base.model.EasyUIDataGrid;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 
 * @author 
 * 
 */
@Service
public class UserLogsService {

    @Autowired
    private BaseDaoI<TuserLogs> userLogsDao;

    /**
     * 获取浏览器类型报表信息
     * 
     * @return
     */
    public List<String> getBrowseType(String searchType, String month) {

        StringBuffer sql = new StringBuffer(
                "SELECT " + searchType + ",count(ID) FROM ade_user_logs WHERE DATE_SUB(CURDATE(),INTERVAL '" + month
                        + "' MONTH) <= date(OPERATE_TIME)GROUP BY " + searchType + "");
        List<Object[]> objs = userLogsDao.findBySql(sql.toString());
        List<String> browserType = new ArrayList<String>();
        for (Object[] obj : objs) {
            String type = obj[0].toString();
            browserType.add(type);
        }
        return browserType;
    }

    /**
     * 获取浏览器类型报表信息
     * 
     * @return
     */
    public List<Integer> getUserNumByBrowseType(String searchType, String month) {
        StringBuffer sql = new StringBuffer(
                "SELECT " + searchType + ",count(ID) FROM ade_user_logs WHERE DATE_SUB(CURDATE(),INTERVAL '" + month
                        + "' MONTH) <= date(OPERATE_TIME)GROUP BY " + searchType + "");
        List<Object[]> objs = userLogsDao.findBySql(sql.toString());
        List<Integer> userNum = new ArrayList<Integer>();
        for (Object[] obj : objs) {
            Integer num = NumberUtils.toInt(obj[1].toString());
            userNum.add(num);
        }
        return userNum;
    }

    public EasyUIDataGrid getUserLogs(UserLogs userLogs, PageHelper ph) {

        EasyUIDataGrid dg = new EasyUIDataGrid();
        List<UserLogs> userLogsList = new ArrayList<UserLogs>();
        Map<String, Object> params = new HashMap<String, Object>();
        StringBuffer hql = new StringBuffer();
        hql.append(" from TuserLogs t ");
        hql.append(whereHql(userLogs, params));
        hql.append(orderHql(ph));
        List<TuserLogs> list = userLogsDao.find(hql.toString(), params, ph.getPage(), ph.getRows());
        if (list != null) {
            for (TuserLogs t : list) {
                UserLogs u = new UserLogs();
                u.setUserName(t.getTuser().getUserName());
                if (t.getLogType() != 0) {
                    BeanUtils.copyProperties(t, u);
                }
                userLogsList.add(u);
            }
        }
        dg.setRows(userLogsList);
        dg.setTotal(userLogsDao.count("select count(*) from TuserLogs t " + whereHql(userLogs, params), params));
        return dg;
    }

    public EasyUIDataGrid getSearchWordsStatistics(PageHelper ph) {

        EasyUIDataGrid dg = new EasyUIDataGrid();
        List<AdminLogs> userLogsList = new ArrayList<AdminLogs>();
        Map<String, Object> params = new HashMap<String, Object>();

        String sql = "SELECT t.VALUE2,COUNT(t.VALUE2) AS num FROM edu_user_logs t WHERE t.LOG_TYPE = :logType GROUP BY t.VALUE2 ORDER BY num DESC";

        List<Object[]> list = userLogsDao.findBySql(sql, params, ph.getPage(), ph.getRows());

        if (list != null) {
            for (Object[] objects : list) {

                AdminLogs u = new AdminLogs();
                u.setValue2(objects[0].toString());
                u.setTimes(Integer.valueOf(objects[1].toString()));
                userLogsList.add(u);
            }
        }
        dg.setRows(userLogsList);
        dg.setTotal(userLogsDao.countBySql("select count(*) from (" + sql + ") t", params).longValue());

        return dg;
    }

    /**
     * 拼接的where语句
     * 
     * @param dingml
     * @param params
     * @return
     */
    private String whereHql(UserLogs userLogs, Map<String, Object> params) {

        StringBuffer hql = new StringBuffer();
        if (userLogs != null) {
            hql.append(" where 1=1 ");
            if (userLogs.getUserId() != null) {
                hql.append(" and t.userId =:userId");
                params.put("userId", userLogs.getUserId());
            }
            if (userLogs.getTimeStart() != null) {
                hql.append(" and t.operateTime >= :timeStart");
                params.put("timeStart", userLogs.getTimeStart());
            }
            if (userLogs.getTimeEnd() != null) {
                hql.append(" and t.operateTime < :timeEnd");
                params.put("timeEnd", userLogs.getTimeEnd());
            }
            if (StringUtils.isNotBlank(userLogs.getLogType())) {
                hql.append(" and t.logType = :logType ");
                params.put("logType", userLogs.getLogType());
            }
        }
        return hql.toString();
    }

    /**
     * 拼接的order语句
     * 
     * @param dingml
     * @param params
     * @return
     */
    private String orderHql(PageHelper ph) {

        String orderString = "";
        if (ph.getSort() != null && ph.getOrder() != null) {
            orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
        }
        return orderString;
    }

    /**
     * 删除历史记录
     * 
     * @param id
     */
    public void deleteUserLog(String id) {
        userLogsDao.delete(userLogsDao.get(TuserLogs.class, id));
    }

    public void log(UserLogs simpleUserLog, Integer logType, String content) {
        log(simpleUserLog, logType, content, null, null);
    }

    public void log(UserLogs simpleUserLog, Integer logType, String content, String value1) {
        log(simpleUserLog, logType, content, value1, null);
    }

    public void log(UserLogs simpleUserLog, Integer logType, String content, String value1, String value2) {

        simpleUserLog.setId(StringUtil.generateUUID());
        simpleUserLog.setValue1(value1);
        simpleUserLog.setValue2(value2);
        simpleUserLog.setContent(content);
        simpleUserLog.setOperateTime(new Date());
        simpleUserLog.setLogType(String.valueOf(logType));

        TuserLogs tuserLogs = new TuserLogs();
        BeanUtils.copyProperties(simpleUserLog, tuserLogs);

        Tuser tuser = new Tuser();
        tuser.setId(simpleUserLog.getUserId());
        tuserLogs.setTuser(tuser);

        userLogsDao.save(tuserLogs);
    }

    public List<UserLogs> getCorrelativeWords(String keyword) {

        String hql = " from TuserLogs t where t.value2 like :keyword and t.logType = :logType group by t.value2 order by t.operateTime desc ";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("keyword", "%" + keyword + "%");

        List<TuserLogs> tlist = userLogsDao.find(hql, params, 0, 10);
        List<UserLogs> list = new ArrayList<UserLogs>();

        for (TuserLogs t : tlist) {
            UserLogs u = new UserLogs();
            // 相关检索词不包含正在检索的词
            if (!keyword.equals(t.getValue2())) {
                u.setValue2(t.getValue2());
                list.add(u);
            }
        }

        return list;

    }

    public List<String> getUserAutoWords(List<String> list, String keyword, String userId) {

        // 获得当前用户的相关检索词
        String hql = " from TuserLogs t where t.tuser.id = :userId and  t.logType = :logType and t.value2 like :keyword group by t.value2 order by t.operateTime desc ";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("keyword", "%" + keyword + "%");

        List<TuserLogs> tlist = userLogsDao.find(hql, params, 0, 10);

        for (TuserLogs t : tlist) {
            list.add(t.getValue2());
        }

        return list;
    }

    public EasyUIDataGrid dataGrid(UserLogs logInfoSys, PageHelper ph, String ids) {

        EasyUIDataGrid dg = new EasyUIDataGrid();

        List<UserLogs> ul = new ArrayList<UserLogs>();

        Map<String, Object> params = new HashMap<String, Object>();

        String hql = " from TuserLogs t  ";

        if (ids != null && !"".equals(ids)) {
            String whereIn = " ";
            for (String tempId : ids.split(",")) {
                tempId = StringUtil.trim(tempId);
                whereIn += ("'" + tempId + "'" + ", ");
            }
            whereIn = whereIn.substring(0, whereIn.lastIndexOf(",")) + " ";
            hql += " and t.id in (" + whereIn + ") ";
        }

        List<TuserLogs> l = userLogsDao.find(hql + whereHql(logInfoSys, params) + orderHql(ph), params, ph.getPage(),
                ph.getRows());
        if (l != null && l.size() > 0) {
            for (TuserLogs t : l) {
                UserLogs d = new UserLogs();
                BeanUtils.copyProperties(t, d);
                d.setUserName(t.getTuser().getLoginName());
                ul.add(d);
            }
        }
        dg.setRows(ul);
        dg.setTotal(userLogsDao.count("select count(*) " + hql + whereHql(logInfoSys, params), params));
        return dg;
    }

    /**
     * 添加至用户日志
     * 
     * @param logInfoUser
     * @param request
     * @throws Exception
     */
    public void add(UserLogs logInfoUser, HttpServletRequest request) {

        TuserLogs t = new TuserLogs();
        // 获得当前IP地址
        BeanUtils.copyProperties(logInfoUser, t);
        if (logInfoUser.getId() == null) {
            t.setId(StringUtil.generateUUID());
            t.setOperateTime(new Date());
            // t.setTuser(userDao.get(Tuser.class, user.getId()));
            userLogsDao.save(t);
        }
    }
}
